<?php

namespace App\Admin\Forms\Withdraw;

use App\Exceptions\AdminException;
use App\Exceptions\ApiException;
use App\Jobs\CreateWalletsJob;
use App\Jobs\SendTransaction;
use App\Models\User;
use App\Models\UserConfig;
use App\Models\UserMill;
use App\Models\UserPerformance;
use App\Models\UserTree;
use App\Models\UserWallet;
use App\Models\UserWithdraw;
use App\Models\WithdrawNotify;
use App\Services\Base\CacheService;
use App\Services\Base\GoogleCaptchaService;
use App\Services\Base\HelpService;
use App\Services\BlockChainApiServices;
use App\Services\BlockChainServices;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class SendTxForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        try {
            /**
             * @var $user_withdraw UserWithdraw
             */
            $user_withdraw = UserWithdraw::query()->find($this->payload['id']);
            if ($user_withdraw->tx_status != TRADE_STATUS_UNTREATED && $user_withdraw->tx_status != TRADE_STATUS_FAIL) {
                return $this
                    ->response()
                    ->success("发送成功，请稍后查询")
                    ->refresh();
            }

            if (!$user_withdraw->to_address) {
                return $this
                    ->response()
                    ->error("接收地址不能为空")
                    ->refresh();
            }

            BlockChainServices::addressSet("TRON", $user_withdraw->to_address);
            $updated_data = ['tx_status' => TX_STATUS_PROCESSING];
            if ($user_withdraw->from_address == "") {
                /**
                 * @var $user_wallet UserWallet
                 */
                $user_wallet = UserWallet::query()->where('status', 1)->first();
                if (!$user_wallet) {
                    return $this
                        ->response()
                        ->error("出款地址不存在")
                        ->refresh();
                }
                $updated_data['from_address'] = $user_wallet->address;
                $chain = $user_withdraw->chain;
                $updated_data['contract'] = config("coins.withdraw_contract.$chain");
            }
            $user_withdraw->update($updated_data);
            $uid = $user_withdraw->uid;
            $cache_key = "withdraw:$uid";
            $frequency = CacheService::getSet($cache_key, 1);
            if ($frequency) {
                throw new ApiException("频率太高");
            }
            SendTransaction::dispatch(1, $user_withdraw)->onQueue("send_transaction");;
            CacheService::del($cache_key);
        } catch (\Exception $e) {
            HelpService::forceLog($e);
            isset($cache_key) && CacheService::del($cache_key);
            $msg = "发送失败";
            if ($e->getCode() == DEFAULT_CODE) {
                $msg = $e->getMessage();
            }
            return $this
                ->response()
                ->error($msg)
                ->refresh();
        }

        return $this
            ->response()
            ->success("发送成功，请稍后查询")
            ->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {

        /**
         * @var $withdraw UserWithdraw
         */
        $withdraw = UserWithdraw::query()->where('id', $this->payload['id'])->first();
        if (!$withdraw) {

        }
        $this->textarea('info', '信息')
            ->value("
提现地址:$withdraw->to_address
提现金额:$withdraw->real_amount
")
            ->disable();

        $this->text('remark', '备注');
        $this->hidden("id")->value($this->getKey());
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        return [
        ];
    }
}
